#!/bin/bash

if [[ $(whoami) != root ]]; then
    echo "must run as root"
    exit
fi

if [[ $# != 1 ]]; then
    echo "$0 install - install this script to be run at boot"
    echo "$0 monitor - the monitoring capability run loop"
    echo "$0 startup - forks into the background and monitors"
    exit
fi

case "$1" in
    install )
        target=/opt/$(basename $0)
        cp $0 $target
        chmod +x $target
        
        if [[ ! -f /etc/rc.d/rc.local ]]; then
            touch /etc/rc.d/rc.local
            echo "#!/bin/bash" >> /etc/rc.d/rc.local
        fi
        if [[ ! -x /etc/rc.d/rc.local ]]; then
            chmod +x /etc/rc.d/rc.local
        fi
        if [[ $(grep $target /etc/rc.d/rc.local) == "" ]]; then
            echo "$target startup" >> /etc/rc.d/rc.local
        fi
        ;;
    monitor )
        next=()
        this=()
        while :; do
            pids=($(ps -e -o comm,pid |
                    egrep "^Chrome_" |
                    sed "s/.* //"))
            
            for pid in ${pids[@]}; do
                if [[ ${this[$pid]} == "" ]]; then
                    next[$pid]=!
                else
                    kill -9 $pid
                fi
            done
            
            this=()
            for pid in ${!next[@]}; do
                this[$pid]=${next[$pid]}
            done
            next=()
            
            sleep 15
        done
        ;;
    startup )
        exec 0>&-
        exec 1>&-
        exec 2>&-
        
        $0 monitor &
        ;;
    *       )
        echo "unknown command"
        ;;
esac
